from pytz import utc,timezone

from app import app


@app.context_processor
def utility_processor():
    def pages_to_jump(max_page, current_page, neighbors=4):
        if max_page < neighbors * 2 + 1:
            return range(1, max_page)

        neighbor_min = current_page - neighbors
        neighbor_max = current_page + neighbors

        if neighbor_max > max_page:
            neighbor_min -= (neighbor_max - max_page)
            neighbor_max = max_page
        elif neighbor_min < 1:
            neighbor_max += (1 - neighbor_min)
            neighbor_min = 1
        return range(neighbor_min, neighbor_max + 1)

    def time_to_str(t, tz=None):
        if tz is None:
            tz = timezone('Asia/Shanghai')
        t = t.replace(tzinfo=utc).astimezone(tz)
        return t.strftime("%A, %d. %B %Y %I:%M%p")

    return dict(pages_to_jump=pages_to_jump,
                time_to_str=time_to_str)
